import { PrismaClient } from '@prisma/client'
import { ClanTemplate, Comment, PaginationParams, PaginatedResponse } from '../types'

const prisma = new PrismaClient()

export class ClanService {
  async getTemplates(params: PaginationParams & { templateType?: string; search?: string } = {}) {
    const { page = 1, limit = 10, templateType, search } = params
    const offset = (page - 1) * limit
    
    const where: any = {}
    
    if (templateType) {
      where.templateType = templateType
    }
    
    if (search) {
      where.OR = [
        { title: { contains: search } },
        { content: { contains: search } },
      ]
    }

    const [templates, total] = await Promise.all([
      prisma.clanTemplate.findMany({
        where,
        skip: offset,
        take: limit,
        include: {
          creator: {
            select: {
              id: true,
              username: true,
              nickname: true,
            },
          },
          _count: {
            select: {
              comments: true,
            },
          },
        },
        orderBy: { createdAt: 'desc' },
      }),
      prisma.clanTemplate.count({ where }),
    ])

    return {
      data: templates,
      pagination: {
        page,
        limit,
        total,
        pages: Math.ceil(total / limit),
      },
    }
  }

  async createTemplate(templateData: Partial<ClanTemplate> & { createdBy: number }) {
    return prisma.clanTemplate.create({
      data: templateData,
      include: {
        creator: {
          select: {
            id: true,
            username: true,
            nickname: true,
          },
        },
      },
    })
  }

  async getTemplateById(id: number) {
    return prisma.clanTemplate.findUnique({
      where: { id },
      include: {
        creator: {
          select: {
            id: true,
            username: true,
            nickname: true,
          },
        },
        comments: {
          include: {
            user: {
              select: {
                id: true,
                username: true,
                nickname: true,
                avatar: true,
              },
            },
            children: {
              include: {
                user: {
                  select: {
                    id: true,
                    username: true,
                    nickname: true,
                    avatar: true,
                  },
                },
              },
            },
          },
          orderBy: { createdAt: 'asc' },
        },
      },
    })
  }

  async updateTemplate(id: number, updateData: Partial<ClanTemplate>) {
    return prisma.clanTemplate.update({
      where: { id },
      data: updateData,
      include: {
        creator: {
          select: {
            id: true,
            username: true,
            nickname: true,
          },
        },
      },
    })
  }

  async deleteTemplate(id: number) {
    return prisma.clanTemplate.delete({
      where: { id },
    })
  }

  async getComments(templateId: number, params: PaginationParams = {}) {
    const { page = 1, limit = 10 } = params
    const offset = (page - 1) * limit
    
    // Get top-level comments
    const [comments, total] = await Promise.all([
      prisma.comment.findMany({
        where: { 
          templateId,
          level: 1,
        },
        skip: offset,
        take: limit,
        include: {
          user: {
            select: {
              id: true,
              username: true,
              nickname: true,
              avatar: true,
            },
          },
          children: {
            include: {
              user: {
                select: {
                  id: true,
                  username: true,
                  nickname: true,
                  avatar: true,
                },
              },
              children: {
                include: {
                  user: {
                    select: {
                      id: true,
                      username: true,
                      nickname: true,
                      avatar: true,
                    },
                  },
                },
              },
            },
          },
        },
        orderBy: { createdAt: 'desc' },
      }),
      prisma.comment.count({
        where: { 
          templateId,
          level: 1,
        },
      }),
    ])

    return {
      data: comments,
      pagination: {
        page,
        limit,
        total,
        pages: Math.ceil(total / limit),
      },
    }
  }

  async createComment(commentData: Partial<Comment> & { templateId: number; userId: number }) {
    const { templateId, userId, content, parentId } = commentData
    
    // Determine comment level
    let level = 1
    if (parentId) {
      const parentComment = await prisma.comment.findUnique({
        where: { id: parentId },
      })
      
      if (!parentComment) {
        throw new Error('Parent comment not found')
      }
      
      // Limit to 3 levels deep
      level = Math.min(parentComment.level + 1, 3)
      
      if (parentComment.level >= 3) {
        throw new Error('Maximum comment depth reached')
      }
    }
    
    return prisma.comment.create({
      data: {
        content,
        templateId,
        userId,
        parentId,
        level,
      },
      include: {
        user: {
          select: {
            id: true,
            username: true,
            nickname: true,
            avatar: true,
          },
        },
        parent: {
          select: {
            id: true,
            content: true,
            user: {
              select: {
                id: true,
                username: true,
                nickname: true,
              },
            },
          },
        },
      },
    })
  }

  async getCommentById(id: number) {
    return prisma.comment.findUnique({
      where: { id },
      include: {
        user: {
          select: {
            id: true,
            username: true,
            nickname: true,
            avatar: true,
          },
        },
        template: {
          select: {
            id: true,
            title: true,
          },
        },
        parent: {
          select: {
            id: true,
            content: true,
            user: {
              select: {
                id: true,
                username: true,
                nickname: true,
              },
            },
          },
        },
        children: {
          include: {
            user: {
              select: {
                id: true,
                username: true,
                nickname: true,
                avatar: true,
              },
            },
          },
        },
      },
    })
  }

  async updateComment(id: number, content: string) {
    return prisma.comment.update({
      where: { id },
      data: { content },
      include: {
        user: {
          select: {
            id: true,
            username: true,
            nickname: true,
            avatar: true,
          },
        },
      },
    })
  }

  async deleteComment(id: number) {
    // Delete comment and all its children
    return prisma.comment.delete({
      where: { id },
    })
  }

  async getTemplateCategories() {
    const types = [
      { value: 'ACTIVITY', label: '活动' },
      { value: 'RULE', label: '族规' },
      { value: 'MEETING', label: '会议' },
      { value: 'VENUE', label: '场所' },
    ]
    
    const counts = await Promise.all(
      types.map(async (type) => {
        const count = await prisma.clanTemplate.count({
          where: { templateType: type.value },
        })
        return {
          ...type,
          count,
        }
      })
    )
    
    return counts
  }

  async getTemplatesByUser(userId: number, params: PaginationParams = {}) {
    const { page = 1, limit = 10 } = params
    const offset = (page - 1) * limit
    
    const [templates, total] = await Promise.all([
      prisma.clanTemplate.findMany({
        where: { createdBy: userId },
        skip: offset,
        take: limit,
        include: {
          creator: {
            select: {
              id: true,
              username: true,
              nickname: true,
            },
          },
          _count: {
            select: {
              comments: true,
            },
          },
        },
        orderBy: { createdAt: 'desc' },
      }),
      prisma.clanTemplate.count({
        where: { createdBy: userId },
      }),
    ])

    return {
      data: templates,
      pagination: {
        page,
        limit,
        total,
        pages: Math.ceil(total / limit),
      },
    }
  }

  async searchTemplates(query: string, params: PaginationParams = {}) {
    const { page = 1, limit = 10 } = params
    const offset = (page - 1) * limit
    
    const [templates, total] = await Promise.all([
      prisma.clanTemplate.findMany({
        where: {
          OR: [
            { title: { contains: query } },
            { content: { contains: query } },
          ],
        },
        skip: offset,
        take: limit,
        include: {
          creator: {
            select: {
              id: true,
              username: true,
              nickname: true,
            },
          },
          _count: {
            select: {
              comments: true,
            },
          },
        },
        orderBy: { createdAt: 'desc' },
      }),
      prisma.clanTemplate.count({
        where: {
          OR: [
            { title: { contains: query } },
            { content: { contains: query } },
          ],
        },
      }),
    ])

    return {
      data: templates,
      pagination: {
        page,
        limit,
        total,
        pages: Math.ceil(total / limit),
      },
    }
  }
}